package com.lw.leetcode.bit.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 835. 图像重叠
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/25 22:32
 */
public class LargestOverlap {


    public static void main(String[] args) {
        LargestOverlap test = new LargestOverlap();

        // 3
        int[][] arr1 = {{1, 1, 0}, {0, 1, 0}, {0, 1, 0}};
        int[][] arr2 = {{0, 0, 0}, {0, 1, 1}, {0, 0, 1}};

        int[][] a = new int[30][30];
        for (int i = 0; i < 30; i++) {
            for (int j = 0; j < 30; j++) {
                a[i][j] = (int) (Math.random() * 2);
            }
        }
        for (int[] ints : a) {
            System.out.print(Arrays.toString(ints) + ",");
        }
        System.out.println();

        // 1
//        int[][] arr1 = {{0,0,0,0,1},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0}};
//        int[][] arr2 = {{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{1,0,0,0,0}};

        int i = test.largestOverlap(arr1, arr2);
        System.out.println(i);
    }

    public int largestOverlap(int[][] img1, int[][] img2) {
        int length = img1.length;
        int[] arr1 = new int[length];
        int[] arr2 = new int[length];
        for (int i = 0; i < length; i++) {
            int[] ints1 = img1[i];
            int[] ints2 = img2[i];
            int v1 = 0;
            int v2 = 0;
            for (int anInt : ints1) {
                v1 = (v1 << 1) + anInt;
            }
            for (int anInt : ints2) {
                v2 = (v2 << 1) + anInt;
            }
            arr1[i] = v1;
            arr2[i] = v2;
        }
        int[] arr11 = new int[length];
        int[] arr22 = new int[length];
        int max = 0;
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length; j++) {
                Arrays.fill(arr11, 0);
                for (int k = j; k < length; k++) {
                    arr11[k - j] = arr1[k] >> i;
                }
                for (int k = 0; k < length; k++) {
                    for (int n = 0; n < length; n++) {
                        Arrays.fill(arr22, 0);
                        for (int m = n; m < length; m++) {
                            arr22[m - n] = arr2[m] >> k;
                        }
                        int sum = 0;
                        for (int m = 0; m < length; m++) {
                            sum += Integer.bitCount(arr11[m] & arr22[m]);
                        }
                        max = Math.max(max, sum);
                    }
                }
            }
        }
        return max;
    }

}
